package org.gw.ylc.base.service;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import org.apache.commons.lang.StringUtils;
import org.gw.ylc.base.model.UserInfo;
import org.gw.ylc.base.repositories.UserInfoRepository;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class UserInfoService {
	// cache for user_info
	private final HazelcastInstance hz;

	private final IMap<String, List<UserInfo>> userInfos;

	private final long userTimoutInSeconds;
	private UserInfoRepository userInfoRepository;

	public UserInfoService(final HazelcastInstance hz, final String mapName, final long userTimoutInSeconds,
			UserInfoRepository userInfoRepository) {
		this.userInfos = hz.getMap(mapName);
		this.userTimoutInSeconds = userTimoutInSeconds;
		this.hz = hz;
		this.userInfoRepository = userInfoRepository;
	}

	/**
	 * 获取用户信息
	 * 
	 * @param username
	 *            工号或者学号，非ID
	 * @param status
	 * @return
	 */
	public List<UserInfo> getUserInfo(String username, int status, String app) {
		if (StringUtils.isBlank(username)) {
			return null;
		}
		List<UserInfo> users = userInfos.get(username);// 一个username可能对应过个userInfo，只是它们的角色不同
		if (users == null) {
			users = userInfoRepository.findByUidAndStatusAndApp(username, status, app);
			if (users != null) {
				userInfos.put(username, users, userTimoutInSeconds, TimeUnit.SECONDS);
			}
		}
		return users;
	}

	public boolean removeFromCache(String username) {
		return userInfos.remove(username) != null;
	}

	public void shutdown() {
		this.hz.shutdown();
	}
}
